package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.CityAdapter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.IndexCityBean;
import com.zhsj.OkeHomeConsumption.other.OnReItemClickListener;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.IndexCityPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.IndexCityUIInterFace;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IndexCityList extends MyActivity implements IndexCityUIInterFace {
    /**
     * 首页城市列表
     */
    @BindView(R.id.city_list)
    RecyclerView cityRecy;
    @BindView(R.id.indexBar)
    IndexBar indexBar;
    @BindView(R.id.tvSideBarHint)
    TextView tvSideBarHint;
    @BindView(R.id.cityname_tv)
    TextView citynameTv;
    @BindView(R.id.ture_button)
    TextView tureButton;
    @BindView(R.id.tb_city_title)
    TitleBar tbCityTitle;
    @BindView(R.id.etSearch)
    EditText etSearch;
    @BindView(R.id.ivDeleteText)
    ImageView ivDeleteText;
    @BindView(R.id.rlSearchFrameDelete)
    RelativeLayout rlSearchFrameDelete;
    @BindView(R.id.top)
    RelativeLayout top;
    private SuspensionDecoration mDecoration;
    private LinearLayoutManager mManager;
    private ArrayList<IndexCityBean> mCityList = null;
    private ArrayList<IndexCityBean> mCityNamestwo;
    private IndexCityPresenter minePersonPresenter;
    private CityAdapter mAdapter;
    Handler myhandler = new Handler();
    /**
     * @Fields mSharedPreferanceUtils : TODO
     */
    private SharedPreferanceUtils mSharedPreferanceUtils = null;

    //定位到的城市
    private String cityLicationStr;
    //定位到的城市ID
    private int locationCityId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_indexcitylist;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_city_title;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        mCityNamestwo = new ArrayList<IndexCityBean>();
        cityLicationStr = getIntent().getStringExtra("locationcity");
        locationCityId = getIntent().getIntExtra("locationCityId", 0);
        citynameTv.setText(cityLicationStr);
        mSharedPreferanceUtils = new SharedPreferanceUtils(getActivity());
        minePersonPresenter = new IndexCityPresenter(getActivity(), this);
        minePersonPresenter.CityListGet();
        cityRecy.setLayoutManager(mManager = new LinearLayoutManager(getActivity()));
        mAdapter = new CityAdapter(this, mCityList);
        cityRecy.setAdapter(mAdapter);

        cityRecy.addItemDecoration(mDecoration = new SuspensionDecoration(this, mCityList));
        //indexbar初始化
        indexBar.setmPressedShowTextView(tvSideBarHint)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(mManager);//设置RecyclerView的LayoutManager
        set_ivDeleteText_OnClick();
        set_eSearch_TextChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 获取城市列表
     */
    @Override
    public void CityListGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mCityList = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<IndexCityBean>>() {
                        }.getType());
                mCityNamestwo = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<IndexCityBean>>() {
                        }.getType());
                initList(mCityList);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("CityListGet", "获取首页城市列表异常");
        }
    }

    private void initList(final ArrayList<IndexCityBean> mCityNames) {
        mAdapter.setDatas(mCityNames);
        mAdapter.notifyDataSetChanged();
        indexBar.setmSourceDatas(mCityNames)//设置数据
                .invalidate();
        mDecoration.setmDatas(mCityNames);
        mAdapter.setOnItemClickListener(new OnReItemClickListener() {
            @Override
            public void onItemClick(View view, Object o, Object q) {
                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                IndexCityBean cityEntity = (IndexCityBean) o;
                mSharedPreferanceUtils.setcityName(cityEntity.getName());
                mSharedPreferanceUtils.setSelectCity(cityEntity.getCityName());
                mSharedPreferanceUtils.setProvinceId(cityEntity.getProvinceId());
                mSharedPreferanceUtils.setSelectCityId(cityEntity.getCityId());
                Hawk.put(Constants.SHARED_PERFERENCE_SELECTCITYID, cityEntity.getCityId());
//                IndexCityPost(cityEntity.getCityId());
                Intent data = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("cityEntity", cityEntity);
                data.putExtras(bundle);
                setResult(RESULT_OK, data);
                finish();
            }
        });
    }

    /**
     * 设置叉叉的点击事件，即清空功能
     */

    private void set_ivDeleteText_OnClick() {
        ivDeleteText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                etSearch.setText("");
                initList(mCityNamestwo);
            }
        });
    }

    private void set_eSearch_TextChanged() {


        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub
                //这个应该是在改变的时候会做的动作吧，具体还没用到过。
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub
                //这是文本框改变之前会执行的动作
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                /**这是文本框改变之后 会执行的动作
                 * 因为我们要做的就是，在文本框改变的同时，我们的listview的数据也进行相应的变动，并且如一的显示在界面上。
                 * 所以这里我们就需要加上数据的修改的动作了。
                 */
                if (s.length() == 0) {
                    ivDeleteText.setVisibility(View.GONE);//当文本框为空时，则叉叉消失
                    initList(mCityNamestwo);
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);//当文本框不为空时，出现叉叉
                    myhandler.post(eChanged);
                }
            }
        });
    }

    Runnable eChanged = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            String data = etSearch.getText().toString();

            mCityList.clear();//先要清空，不然会叠加

            getmDataSub(mCityList, data);//获取更新数据
            initList(mCityList);
//             mAdapter.notifyDataSetChanged();//更新

        }
    };

    /**
     * 获得根据搜索框的数据data来从元数据筛选，筛选出来的数据放入mDataSubs里
     *
     * @param
     * @param data
     */

    private void getmDataSub(ArrayList<IndexCityBean> mCityNamess, String data) {
        for (int i = 0; i < mCityNamestwo.size(); ++i) {
            if (mCityNamestwo.get(i).getShowName().contains(data) || mCityNamestwo.get(i).getName().contains(data)) {
                mCityNamess.add(mCityNamestwo.get(i));
            }

        }
    }

    @OnClick(R.id.ture_button)
    public void onViewClicked() {
        if (!cityLicationStr.equals("定位失败")) {
            mSharedPreferanceUtils.setcityName(cityLicationStr);
            mSharedPreferanceUtils.setSelectCityId(locationCityId);
        }
        finish();
    }
}
